package com.ybu.oodd.utils.ai;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ybu.oodd.pojo.AIResult;
import com.ybu.oodd.pojo.PageResult;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class AIResumeProcessor {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 解析输入的 JSON 字符串，返回 PageResult<AIResult>
     *
     * @param jsonString 输入的 JSON 字符串
     * @return 成功时返回 PageResult<AIResult>，失败时返回 null
     */
    public static PageResult<AIResult> parseAIResumeResult(String jsonString) {
        try {
            JsonNode root = objectMapper.readTree(jsonString);

            // 判断 status 字段
            JsonNode statusNode = root.get("status");
            if (statusNode == null) {
                log.warn("Missing 'status' field in input JSON");
                return null;
            }

            String status = statusNode.asText();
            if (!"success".equals(status)) {
                log.info("Processing failed, status: {}", status);
                return null;
            }

            // 获取 total
            JsonNode totalNode = root.get("total");
            if (totalNode == null) {
                log.warn("Missing 'total' field in input JSON");
                return null;
            }
            Long total = totalNode.asLong();

            // 获取 rows 数组
            JsonNode rowsNode = root.get("rows");
            if (rowsNode == null || !rowsNode.isArray()) {
                log.warn("Missing or invalid 'rows' field in input JSON");
                return null;
            }

            List<AIResult> aiResults = new ArrayList<>();
            for (JsonNode row : rowsNode) {
                String before = row.has("before") ? row.get("before").asText() : "";
                String after = row.has("after") ? row.get("after").asText() : "";
                aiResults.add(new AIResult(before, after));
            }

            return new PageResult<AIResult>(total, aiResults);

        } catch (IOException e) {
            log.error("Failed to parse JSON string: {}", jsonString, e);
            return null;
        }
    }
}